<template>
  <view>
    <l-info-list-cell label="切换身份" arrow unlined :value="userInfo ? userInfo.companyName : ''" @click="showIdentityList" />

    <tui-actionsheet :show.sync="showActionSheet" :item-list="itemList" @click="changeUser" />

    <log-out-dialog :show.sync="showLogOutDialog" :phone="dialogPhone" @confirm="changeUser(changeUserInfo)" />
  </view>
</template>

<script>
import logOutDialog from '../log-out-dialog/log-out-dialog'
import { mapGetters, mapMutations } from 'vuex'
import { getUserList, changeUser } from '@/common/api/user'
export default {
  name: 'UserIdentityList',
  components: {
    logOutDialog
  },
  data() {
    return {
      showActionSheet: false,
      showLogOutDialog: false,
      dialogPhone: '',
      changeUserInfo: {}
    }
  },
  computed: {
    itemList() {
      return this.identityList.map(item => {
        const zIndex = item.companyName === this.userInfo && this.userInfo.companyName ? 'primary' : 'secondary'
        return {
          text: item.companyName || item.nickname,
          userId: item.userId,
          zIndex
        }
      })
    },
    ...mapGetters({
      identityList: 'identityList',
      userInfo: 'userInfo',
      userId: 'userId'
    })
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取身份列表
    async getUserList() {
      const [err, res] = await getUserList({
        identityTypes: 'autoCompany'
      })
      if (!this.$http.errorCheck(err, res)) return false
      const list = res.data.data
      this.setIdentityList(list)
    },
    // 显示身份列表
    showIdentityList() {
      if (this.identityList.length > 1) {
        this.showActionSheet = true
      }
    },
    // 切换身份
    async changeUser(e) {
      this.showActionSheet = false
      this.changeUserInfo = e
      const userId = e.userId
      if (userId !== this.userId) {
        const [err, res] = await changeUser({ userId })
        if (!this.$http.errorCheck(err, res)) return false
        const data = res.data
        if (data.accountStatus === 1) {
          // 身份注销中，提示取消注销
          this.dialogPhone = data.phone.substring(0, 3) + '****' + data.phone.substring(7, 11)
          this.showLogOutDialog = true
        } else if (data.access_token) {
          this.changeUserInfo = {}
          this.toast('切换成功')
          this.login.saveLoginInfo(res)
          await this.login.getVipRecord()
        }
      } else {
        this.changeUserInfo = {}
        this.toast('当前已为' + this.userInfo.companyName)
      }
    },
    ...mapMutations({
      setIdentityList: 'user/setIdentityList'
    })
  }
}
</script>

<style scoped>

</style>
